package ifgi.potwc.ipt.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * This class handles saving and updating data in the database.
 * 
 * @author saschak.
 */
public class IptDatabaseManager
{
    // Database
    private IptDatabase iptDb;
    private SQLiteDatabase db;

    /**
     * Returns the database.
     * 
     * @return
     */
    public SQLiteDatabase getDb()
    {
	return db;
    }

    /**
     * Constructor.
     * 
     * @param _context
     */
    public IptDatabaseManager(Context _context)
    {
	iptDb = new IptDatabase(_context);
	db = iptDb.getWritableDatabase();
    }

    /**
     * Saves feed ID, timestamp, and value for a datastream in the database.
     * 
     * @param _feedID
     * @param _timestamp
     * @param _value
     * @param _datastream
     */
    public void saveValuesInDatabase(String _feedID, String _timestamp,
	    double _value, String _datastream)
    {
	ContentValues cv = new ContentValues();
	cv.put(IptDatabase.FEED_ID, _feedID);
	cv.put(IptDatabase.UPLOADED, 0);
	cv.put(IptDatabase.TIMESTAMP, _timestamp);
	cv.put(_datastream, _value);

	db.insert(_datastream + IptDatabase.TABLE_TAG, null, cv);
    }

    /**
     * Updates all rows of the given table with the given feed ID as "uploaded"
     * which means the integer value is changed from 0 = "not uploaded" to 1 =
     * "uploaded".
     * 
     * @param _feedID
     * @param _datastream
     */
    public void markTableRowsAsUploaded(String _feedID, String _datastream)
    {
	// Change "uploaded" to 1 for all rows in the table that have the given
	// Feed ID and where "uploaded" = 0
	ContentValues cv = new ContentValues();
	cv.put(IptDatabase.UPLOADED, 1);

	db.update(_datastream + IptDatabase.TABLE_TAG, cv, IptDatabase.UPLOADED
		+ " = 0 AND " + IptDatabase.FEED_ID + "=?",
		new String[] { _feedID });
    }
}